#include <libipc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <getopt.h>
#include <signal.h>

int boiterequete;
int boitereponse;

void handler(int signum) {		/* traitement SIGINT */
	printf("reception SIGINT\n");
	struct message* m = malloc(sizeof(struct message));
	m->code = 5;
	m->coupe = 0;
	m->numpacket = 1;
	envoyer_message(boiterequete, m);
	free(m);
	close_boite(boitereponse);
	exit(0);
}

int main(int argc, char *argv[]) {
	boitereponse = creer_boite_private(boitereponse);	/* unique pour chaque lancement du main */
	boiterequete = connect_boite_requete(NUMBOITEREQ);
	struct message* m = malloc(sizeof(struct message));
	m->boitereponse = boitereponse;

	struct sigaction signal;
	signal.sa_handler = handler;
	signal.sa_flags = SA_RESTART;
	if (sigaction(SIGINT, &signal, NULL) == -1) {
		perror("sigaction");
		exit(-1);
	}

	static struct option long_options[] = { { "users", 0, 0, 'u' }, {
			"connected", 0, 0, 'c' }, { "add-user", 1, 0, 'a' }, { "listen", 0,
			0, 'l' }, { 0, 0, 0, 0 } };									/* differente option possible */
	int c;
	int option_index = 0;
	while (1) {
		c = getopt_long(argc, argv, "ucla:", long_options, &option_index);
		if (c == -1) {
			break;
		}
		switch (c) {
		case 'u':
			m->code = 1;
			m->coupe = 0;
			m->numpacket = 1;
			break;
		case 'c':
			m->code = 2;
			m->coupe = 0;
			m->numpacket = 1;
			break;
		case 'a': /* pour ajouter user utiliser forme  " pseudo:psswd:Prenom-Nom " */
			m->code = 3;
			m->coupe = 0;
			m->numpacket = 1;
			strncpy(m->buffer, optarg, strlen(optarg));
			break;
		case 'l':
			m->code = 4;
			m->coupe = 0;
			m->numpacket = 1;
			break;
		case '?':
			return -1;
		default:
			break;
		}
	}
	envoyer_message(boiterequete, m);
	// recevoir le message de réponse
	struct message* mreponse = malloc(sizeof(struct message));
	do {
		recevoir_message(boitereponse, mreponse);		/* pas de traitement particulier en cas de coupe */
		printf("%s", mreponse->buffer);					/* les messages peuvent se retrouver desordonnes */
		bzero(mreponse->buffer,SIZEBUF);
	} while (mreponse->coupe != 0);
	printf("\n");
	free(mreponse);
	free(m);
	close_boite(boitereponse);
	return 0;
}
